package j.framework.tags.easyui;

import j.framework.tags.TagUtils;
import j.framework.tags.form.FormTagWriter;
import j.util.New;
import j.util.StringUtils;
import j.util.json.JsonUtils;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.Map;

/**
 * 所有的easyui form控件从此继承
 * User: jason
 * Date: 2015/1/16 15:47
 */
public abstract class BaseEasyuiFormControl extends TagSupport {
    protected String name;
    private boolean required;
    private String prompt;
    private String dataArgs;
    private String tipPosition;//验证信息显示的位置
    private String validType;//验证类型，如：email、url等
    private String dataOptions;
    private String style;
    private boolean disabled;
    private boolean readonly;

    public abstract void writeFormTagBegin(FormTagWriter writer) throws JspException;
    public abstract void writeFormTagProperties(FormTagWriter writer) throws JspException;
    public abstract void writeEasyuiDataOptions(Map<String,Object> dataOptions) throws JspException;
    public abstract void endBeginTag(FormTagWriter writer) throws JspException;
    public abstract String getEasyuiClassName();

    /**
     * 在用户没有指定style width的情况下，调用子类来获取其默认宽度，这个宽度的单位（像素或百分比）均由子类决定；
     * @return
     */
    protected abstract String getControlWidth();

    protected Object getFormDataValue(){
        j.framework.tags.form.FormTag formTag = TagUtils.getParentAsFormTag(this);
        if(null!=formTag){
            return formTag.getFormDataValue(name);
        }
        return null;
    }

    @Override
    public int doStartTag() throws JspException {
        j.framework.tags.form.FormTag formTag = TagUtils.getParentAsFormTag(this);
        FormTagWriter writer;
        if(null!=formTag){
            writer = formTag.getWriter();
        }else{
            writer = new FormTagWriter(this.pageContext.getOut());
        }
        //先写入标签的开始
        writeFormTagBegin(writer);
        //写入标签的ID及名称，即name
        writer.writeFormTagProperty("id", name);
        writer.writeFormTagProperty("name", name);
        writer.writeFormTagProperty("data-args",dataArgs);
        //由子类写入标签的个性部分
        writeFormTagProperties(writer);
        writer.writeFormTagProperty("class", getEasyuiClassName());
        Map<String,Object> dataOptions = New.map();
        if(required){
            dataOptions.put("required",true);
        }
        if(disabled){
            dataOptions.put("disabled",true);
        }
        if(readonly){
            dataOptions.put("readonly",true);
        }
        if(StringUtils.isNotEmpty(prompt)){
            dataOptions.put("prompt",prompt);
        }
        writeEasyuiDataOptions(dataOptions);
        if(StringUtils.isNotEmpty(this.dataOptions)){
            dataOptions.putAll(JsonUtils.parseMap(String.format("{%s}", this.dataOptions)));
        }
        if(StringUtils.isNotEmpty(this.tipPosition)){
            dataOptions.put("tipPosition", this.tipPosition);
        }else{
            dataOptions.put("tipPosition", "bottom");
        }
        if(StringUtils.isNotEmpty(this.validType)){
            dataOptions.put("validType",this.validType);
        }
        if(dataOptions.size()>0){
            //write data-options
            writer.writeSomething(" data-options=\"");
            StringBuilder s = new StringBuilder();
            Object optionValue;
            for(Map.Entry<String,Object> entry : dataOptions.entrySet()){
                optionValue = entry.getValue();
                if(null == optionValue){
                    continue;
                }
                s.append(entry.getKey()).append(":");
                if(entry.getKey().startsWith("on")
                        || entry.getKey().equals("searcher")){
                    //这是事件类的属性
                    s.append(String.valueOf(optionValue)).append(",");
                    continue;
                }
                if(optionValue instanceof String){
                    s.append("'").append(optionValue).append("'");
                }else{
                    s.append(optionValue);
                }
                s.append(",");
            }
            if(s.length()>0){
                s.deleteCharAt(s.length()-1);
            }
            writer.writeSomething(s.toString());
            writer.writeSomething("\"");
        }

        String _style = style;
        String _controlWidth = getControlWidth();
        if(StringUtils.isNullOrEmpty(_controlWidth)){
            _controlWidth = "100%";
        }
        if(StringUtils.isNotEmpty(_controlWidth)){
            if (StringUtils.isNullOrEmpty(style)) {
                _style = "width:"+_controlWidth;
            } else if (!_style.contains("width:")) {
                if (!_style.endsWith(";")) {
                    _style += ";";
                }
                _style += "width:"+_controlWidth;
            }
        }
        if(StringUtils.isNotEmpty(_style)){
            writer.writeFormTagProperty("style",_style);
        }
        //结束标签的开始写入
        endBeginTag(writer);
        return SKIP_BODY;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    public void setPrompt(String prompt) {
        this.prompt = prompt;
    }

    public void setDataArgs(String dataArgs) {
        this.dataArgs = dataArgs;
    }

    public void setTipPosition(String tipPosition) {
        this.tipPosition = tipPosition;
    }

    public void setValidType(String validType) {
        this.validType = validType;
    }

    public void setDataOptions(String dataOptions) {
        this.dataOptions = dataOptions;
    }

    public void setStyle(String style) {
        this.style = style;
    }

    public void setDisabled(boolean disabled) {
        this.disabled = disabled;
    }

    public void setReadonly(boolean readonly) {
        this.readonly = readonly;
    }
}
